import { http } from './axios';

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }

    // 统一错误处理
    const errorMessage = error.response?.data?.message || error.response?.data?.error || '请求失败';
    return Promise.reject({
      message: errorMessage,
      code: error.response?.status,
      data: error.response?.data
    });
  }
);

export default http;